/**
 * @author 魏文杰
 */

package ext.tianma.bom.workflow;

import java.rmi.RemoteException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import com.ptc.windchill.enterprise.part.commands.PartDocServiceCommand;

import wt.doc.WTDocument;
import wt.fc.ObjectReference;
import wt.fc.QueryResult;
import wt.fc.collections.WTArrayList;
import wt.lifecycle.State;
import wt.part.WTPart;
import wt.util.WTException;
import wt.util.WTRuntimeException;
import wt.vc.config.ConfigException;
import wt.vc.wip.WorkInProgressHelper;
import ext.com.iba.IBAUtil;
import ext.com.workflow.WorkflowUtil;
import ext.generic.erp.common.CommonPDMUtil;
import ext.generic.erp.service.BOMReleaseService;
import ext.generic.erp.util.BOMStructureUtil;
import ext.tianma.part.forms.TMTypeUtil;

public class ReWriteConversionThroughputBusiness {
	//新品状态
	private static final String NEW_PRODUCT = "NewProduct" ;
	
	//量产发布
	private static final String MASS_PRODUCTION_RELEASE = "MassProductionRelease" ;
	
	//批准
	private static final String APPROVAL = "APPROVAL" ;
	
	//试产
	private static final String TRIAL_PRODUCTION = "TrialProduction";
	
	//小批量
	private static final String  CUSTOMER_SAMPLE = "CustomerSample";
	
	//风险批量
	private static final String RISK_ORDER = "RiskOrder";
	
 	public static void showPageData(Object pbo , WTArrayList reviewObjs , WTArrayList  tableData) throws WTException{
		
    	if(pbo == null || !(pbo instanceof WTDocument)){
    		System.out.println("传入进来的对象"+pbo+"为空或者不是【WTDocument】类型的对象，直接返回空！");
    		return ;
    	}
    	
	    WTDocument doc = (WTDocument) pbo;
	    
	    List<WTPart> allPart = getAllRelatedParts( doc );
		    	
    	//初始化传入来的两个参数 
    	if(reviewObjs == null){
    		reviewObjs = new WTArrayList();
    	}else{
    		reviewObjs.clear();
    	}
    	
    	reviewObjs.add(doc);
    	
		if(tableData == null){
			tableData = new WTArrayList();	
		}else{
			tableData.clear();
		}
		
		checkAllParts( allPart , reviewObjs , tableData ) ;
	    
		//checkPartsIsCheckOut( allPart ) ;
		
	}
	
	public static void checkPartsIsCheckOut( Object pbo ) throws WTException {
		if(pbo == null || !(pbo instanceof WTDocument)){
    		System.out.println("传入进来的对象"+pbo+"为空或者不是【WTDocument】类型的对象，直接返回空！");
    		return ;
    	}
    	
	    WTDocument doc = (WTDocument) pbo;
	    
	    List<WTPart> allPart = getAllRelatedParts( doc );
	    
	    checkPartsIsCheckOut( allPart );
	}

	public static void checkPartsIsCheckOut( List<WTPart> parts ) throws WTException {
		//保存被检出部件的编号
		StringBuffer checkoutInfo = new StringBuffer("") ;
		
		Iterator<WTPart> ite = parts.iterator() ;
		while( ite.hasNext() ){
			WTPart part = ite.next() ;
			
			if( part != null ){
				if(WorkInProgressHelper.isCheckedOut( part )){
					checkoutInfo.append(part.getNumber()) ;
					checkoutInfo.append(" , " ) ;
					checkoutInfo.append(part.getViewName()) ;
					checkoutInfo.append(" , " ) ;
					checkoutInfo.append(CommonPDMUtil.getVersion(part)) ;
					checkoutInfo.append("\n") ;
				}
			}
		}
		
		if( checkoutInfo.length() > 0 ){
			throw new WTException("以下零部件被检出：\n" + checkoutInfo.toString());
		}
	}
	
	private static List<WTPart> getAllRelatedParts( WTDocument doc ) throws WTException {
		List<WTPart> allPart = new ArrayList<WTPart>();
		
		//获取当前文档所关联的所有零部件
	    QueryResult refPartQR = ext.com.core.CoreUtil.getAssociatedParts(doc);
	    
	    while (refPartQR.hasMoreElements()) {
			Object refObj = refPartQR.nextElement();
			
			if (refObj !=null && refObj instanceof WTPart) {
			    WTPart part = (WTPart) refObj;
			    
			    //将文档关联的零部件加入List
			    allPart.add(part);
			    
			 	//递归获得所有的子部件
		    	//ArrayList<WTPart> allSubPart = BOMBusinessUtil.getAllSubPart(part);
			    //List<WTPart> allSubPart = getAllSubParts( part ) ;
			    
			    //包含特地替代料
			    List<WTPart> allSubPart = ReWriteBOMReviewConfirmBusiness.getAllSubPartsWithSubstitute(part) ;
			    
		    	System.out.println("指定对象【"+part.getDisplayIdentifier()+"】下包含的所有子部件个数是："+allSubPart.size());
		    	
		    	//将所有子件加入List
		    	allPart.addAll(allSubPart);
			}
	    }
	    
	    return allPart ;
	}
	
	public static List<WTPart> getAllSubParts(WTPart part){
		List<WTPart> subPartList = new ArrayList<WTPart>() ;
		
		if( part == null ){
			return  subPartList ;
		}
		
		//构造Map，通过编号过滤重复的零部件
		Map<String,WTPart> partNumberMap = new HashMap<String,WTPart>() ;
		
		try {
			List<WTPart> childList = BOMStructureUtil.getFirstLevelChildren(part) ;
			
			while( childList != null && childList.size() > 0 ){
				System.out.println("Debug    childList:"+childList.size());
				List<WTPart> tempList = new ArrayList<WTPart>() ;
				
				Iterator<WTPart> ite = childList.iterator() ;
				
				while( ite.hasNext() ){
					WTPart childPart = ite.next() ;
					
					String childPartNumber = childPart.getNumber() ;
					
					if( ! partNumberMap.containsKey( childPartNumber ) ){
						partNumberMap.put( childPartNumber , childPart );
						
						tempList.addAll( BOMStructureUtil.getFirstLevelChildren( childPart ) ) ;
					}
				}
				
				childList = tempList ;
			}
		} catch (ConfigException e) {
			e.printStackTrace();
		} catch (WTException e) {
			e.printStackTrace();
		}
		
		subPartList.addAll( partNumberMap.values() );
		
		return subPartList ;
	}
	
	private static void checkAllParts( List<WTPart> allPart , WTArrayList reviewObjs , WTArrayList tableData ) {
		Iterator<WTPart> ite = allPart.iterator() ;
		
		while( ite.hasNext() ){
			WTPart part = ite.next() ;
			
			if( TMTypeUtil.isRawMaterial( part ) ){
				
				//处理原材料
				checkRawMaterial( part , reviewObjs , tableData );
				
			}else if( TMTypeUtil.isSemiFinishedGood( part ) ) {
				
				//处理半成品
				checkSemiFinishedGood( part , reviewObjs , tableData );
				
			}else if( TMTypeUtil.isFinishedGood( part ) ) {
				
				//处理成品
				checkFinishedGood( part , reviewObjs , tableData );
				
			}
		}
	}
	
	private static void checkRawMaterial( WTPart part , WTArrayList reviewObjs , WTArrayList tableData ){
		String currentState = part.getLifeCycleState().toString();
		
		System.out.println("当前对象【"+ part.getDisplayIdentifier()+"】的生命周期是："+currentState);
		
		//如果原材料状态为量产发布，则不处理
		if(currentState.equals(MASS_PRODUCTION_RELEASE)){
			return ;
		}
		//如果原材料状态为新品
		else if( currentState.equals(NEW_PRODUCT) ){
			try {
				//是否需要样品承认
				String partRecognize = (String) IBAUtil.getIBAValue( part , "partRecognize");
				
				//是否已经样品承认
				String whetherPartRecognize = (String) IBAUtil.getIBAValue( part , "whetherPartRecognize" );
				
				//如果属性值为否
	    		if( ( partRecognize != null && partRecognize.equals("否") ) && ( whetherPartRecognize == null || whetherPartRecognize.trim().isEmpty() ) ){
	    			reviewObjs.add( part ) ;
	    			
	    			return ;
	    		}
	    		else if( ( partRecognize != null && partRecognize.equals( "是" ) ) && ( whetherPartRecognize != null && whetherPartRecognize.equals( "是" ) ) ){
	    			reviewObjs.add( part ) ;
	    			
	    			return ;
	    		}
	    		else{
	    			tableData.add( part );
	    			
	    			return ;
	    		}
			} catch (RemoteException e) {
				e.printStackTrace();
			} catch (WTException e) {
				e.printStackTrace();
			}
		}
		//如果原材料状态为批准
//		else if( currentState.equals(APPROVAL) ){
//			try {
//				//是否需要样品承认
//				String partRecognize = (String) IBAUtil.getIBAValue( part , "partRecognize");
//				//是否已经样品承认
//				String whetherPartRecognize = (String) IBAUtil.getIBAValue( part , "whetherPartRecognize" );
//				
//				//如果属性值为是
//	    		if( ( partRecognize != null && partRecognize.equals( "是" ) ) && ( whetherPartRecognize != null && whetherPartRecognize.equals( "是" ) ) ){
//	    			reviewObjs.add( part ) ;
//	    			
//	    			return ;
//	    		}else{
//	    			tableData.add( part );
//	    			
//	    			return ;
//	    		}
//			} catch (RemoteException e) {
//				e.printStackTrace();
//			} catch (WTException e) {
//				e.printStackTrace();
//			}
//		}
		// 如果原材料生命周期状态为其他状态，则记录到不合格列表中
		else{
			tableData.add( part );
			
			return ;
		}
	}
	
	private static void checkSemiFinishedGood( WTPart part , WTArrayList reviewObjs , WTArrayList tableData ){
		String currentState = part.getLifeCycleState().toString();
		
		System.out.println("当前对象【"+ part.getDisplayIdentifier()+"】的生命周期是："+currentState);
		
		//如果半成品生命周期状态为量产发布，则不处理
		if(currentState.equals(MASS_PRODUCTION_RELEASE)){
			return ;
		}
		//如果半成品生命周期状态为新品，则记录到随签列表中
		else if(currentState.equals(NEW_PRODUCT)){
			reviewObjs.add( part ) ;
			
			return ;
		}
		//如果半成品生命周期状态为试产，则记录到随签列表中
		else if(currentState.equals(TRIAL_PRODUCTION)) {
			reviewObjs.add( part );
					
			return ;
		}
		//如果半成品生命周期状态为小批量，则记录到随签列表中
		else if(currentState.equals(CUSTOMER_SAMPLE)) {
			reviewObjs.add( part );
			
			return;
		}
		//如果半成品生命周期状态为风险批量，则记录到随签列表中
		else if(currentState.equals(RISK_ORDER)) {
			reviewObjs.add( part );
			
			return;
		}
		// 如果半成品生命周期状态为其他状态，则记录到不合格列表中
		else{
			tableData.add( part );
			
			return ;
		}
	}
	
	/**
	 * 试产转量产 新品转量产
	 * @param part
	 * @param reviewObjs
	 * @param tableData
	 */
	private static void checkFinishedGood( WTPart part , WTArrayList reviewObjs , WTArrayList tableData ){
		String currentState = part.getLifeCycleState().toString() ;
		
		System.out.println("当前对象【"+ part.getDisplayIdentifier()+"】的生命周期是："+currentState);
		
		//如果成品生命周期状态为量产发布，则不处理
		if(currentState.equals(MASS_PRODUCTION_RELEASE)){
			return ;
		}
		//如果成品生命周期状态为新品，则记录到随签列表中
		else if(currentState.equals(NEW_PRODUCT)){
			reviewObjs.add( part ) ;
			
			return ;
		}
		//如果成品生命周期状态为试产，则记录到随签列表中
		else if(currentState.equals(TRIAL_PRODUCTION)) {
			reviewObjs.add( part );
			
			return ;
		}
		//如果成品生命周期状态为小批量，则记录到随签列表中
		else if(currentState.equals(CUSTOMER_SAMPLE)) {
			reviewObjs.add( part );
					
			return;
		}
		//如果成品生命周期状态为风险批量，则记录到随签列表中
		else if(currentState.equals(RISK_ORDER)) {
			reviewObjs.add( part );
					
			return;
		}
		// 如果成品生命周期状态为其他状态，则记录到不合格列表中
		else{
			tableData.add( part );
			
			return ;
		}
	}
	
	/**
	 * 根据转量产类型，设置小批量、风险批量、量产发布状态
	 * @param part
	 * @param reviewObjs
	 * @throws WTException
	 * 2018-09-17
	 */
	public static void setReviewObjsState(Object obj,WTArrayList reviewObjs){
		WTDocument doc = null; 
		if( obj == null ){
			return;
		}
		if(obj instanceof ObjectReference){
			ObjectReference ref = (ObjectReference) obj;
			obj = ref.getObject();
		}
		
		if(obj instanceof WTDocument){
			doc = (WTDocument) obj;	
		}

		if(doc != null && !"".equals(doc)){
			try {
				Object productionType = null;
				productionType = IBAUtil.getIBAValue(doc,"ProducttionType");
				reviewObjs = BOMBusinessUtil.getLatestWTPartByView(reviewObjs);
				for(int i = 0;i<reviewObjs.size();i++) {
					ObjectReference partref = (ObjectReference)reviewObjs.get(i);
					Object partobj = partref.getObject();
					WTPart part = (WTPart)partobj;
		
					if(TMTypeUtil.isFinishedGood(part) || TMTypeUtil.isSemiFinishedGood(part)) {
						String state = part.getLifeCycleState().toString();
						if("RO".equals(productionType)) {
							if(state.equals(NEW_PRODUCT)||state.equals(TRIAL_PRODUCTION)) {
								part = (WTPart)WorkflowUtil.setLifeCycleState( part, RISK_ORDER );
								List<WTPart> allPart = ReWriteBOMReviewConfirmBusiness.getAllSubPartsWithSubstitute(part);
								for (WTPart wtPart : allPart) {
									if(TMTypeUtil.isFinishedGood(wtPart) || TMTypeUtil.isSemiFinishedGood(wtPart)){
										if(NEW_PRODUCT.equals(wtPart.getLifeCycleState().toString())||TRIAL_PRODUCTION.equals(wtPart.getLifeCycleState().toString())){
											wtPart = (WTPart)WorkflowUtil.setLifeCycleState( wtPart, RISK_ORDER );
										}
									}else if(TMTypeUtil.isRawMaterial(wtPart)){
										if(NEW_PRODUCT.equals(wtPart.getLifeCycleState().toString())||APPROVAL.equals(wtPart.getLifeCycleState().toString())){
											wtPart = (WTPart)WorkflowUtil.setLifeCycleState( wtPart, MASS_PRODUCTION_RELEASE );
										}
									}
								}
							}
						}else if("CS".equals(productionType)) {
							if(state.equals(NEW_PRODUCT)||state.equals(TRIAL_PRODUCTION)||state.equals(RISK_ORDER)) {
								part = (WTPart)WorkflowUtil.setLifeCycleState( part, CUSTOMER_SAMPLE );
								List<WTPart> allPart = ReWriteBOMReviewConfirmBusiness.getAllSubPartsWithSubstitute(part);
								for (WTPart wtPart : allPart) {
									if(TMTypeUtil.isFinishedGood(wtPart) || TMTypeUtil.isSemiFinishedGood(wtPart)){
										if(NEW_PRODUCT.equals(wtPart.getLifeCycleState().toString())||TRIAL_PRODUCTION.equals(wtPart.getLifeCycleState().toString())||RISK_ORDER.equals(wtPart.getLifeCycleState().toString())){
											wtPart = (WTPart)WorkflowUtil.setLifeCycleState( wtPart, CUSTOMER_SAMPLE );
										}
									}else if(TMTypeUtil.isRawMaterial(wtPart)){
										if(NEW_PRODUCT.equals(wtPart.getLifeCycleState().toString())||APPROVAL.equals(wtPart.getLifeCycleState().toString())){
											wtPart = (WTPart)WorkflowUtil.setLifeCycleState( wtPart, MASS_PRODUCTION_RELEASE );
										}
									}
								}
							}
						}
						else if("MP".equals(productionType)) {
							BOMBusinessUtil.setLifeCycleState(reviewObjs, MASS_PRODUCTION_RELEASE);
						}
						System.out.println("转量产类型：" + productionType);
					}
				}
			} catch (RemoteException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (WTRuntimeException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (WTException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}			
	}		
	
		
}
